adminPanel.controller('StudentAcedemicsCntlr',['$scope', '$filter', '$http', '$q','cacheFactory', function($scope, $filter, $http, $q,cacheFactory) {
	$q;	
	$scope.subjects=cacheFactory.getSubjects();
	$scope.gradeList=cacheFactory.getGradeList();
	$scope.termList=cacheFactory.getTermList();
	$scope.gradePoints=cacheFactory.getGradePoints();
	$scope.showGrid=false;
	
	//use to send data to server
	var studentRecord={"studentAcademics":null, "searchCriteria":null};
	$scope.searchCriteria.recordType='ACADEMICS';
	//get the subjects loaded into system
	$scope.academicVos =[];
	$scope.academicExtraInfo=[];
	
	//called after file attached by user.
	$scope.handleAttachImage=function(data){
		if(data.status=='SUCCESS'){
			$scope.academicExtraInfo.list.push(data.result[0]);
		}else{
			ERROR_LOGGER(data);
		}
		$('#myModal').modal('toggle');
	}
	
	$scope.recommendations=[];
	$scope.showRecommendation=false;
	$scope.handleSavedRecommendation=function(data){
		if(data.type=='SAVE_RECOMMENDATION'){
			$scope.getRecommendations();
		}
	}
	$scope.handleDeletedRecommendation=function(data){
		if(data.type=='DELETE_RECOMMENDATION'){
			$scope.getRecommendations();
		}
	}
	
	
	$scope.getRecommendations=function(){
	    var httpResult=$http.post(BASE_URL+'admin/handleRequest/studentRecord/RECOMMENDATION_GET', {searchCriteria:$scope.searchCriteria});
	    httpResult.success(function(data){
	    	if(data.status=='SUCCESS'){
	    		$scope.recommendations=data.result;
	    		$scope.showRecommendation=true;
	    	}else{
	    		$scope.showRecommendation=false;
	    	}
	    });
	}
	//register event
	  RegisterEventHandler("StudentAcedemicsCntlr",$scope.handleDeletedRecommendation);
	  RegisterEventHandler("StudentAcedemicsCntlr1",$scope.handleSavedRecommendation);
	
	//called after file attached by user.
	$scope.handleDeleteImage=function(data){
		if(data.status=='SUCCESS'){
			//if success remove file from ui
			$scope.academicExtraInfo.list = $filter('filter')($scope.academicExtraInfo.list, {id: data.result[0].id},function(obj,test){return obj!==test});
		}else{
			ERROR_LOGGER(data);
		}
	}
	
	//called after file attached by user.
	$scope.handleDownloadImage=function(data){
		if(data.status=='SUCCESS'){
			alert(data);
		}else{
			ERROR_LOGGER(data);
		}
	}
	
	$scope.getDetails= function(){                 
		studentRecord.searchCriteria= $scope.searchCriteria;
		$http.post(BASE_URL+"admin/handleRequest/studentRecord/GET_ACADEMICS_BY_GRADE_AND_TERM/",studentRecord).success(function(data){
			if(data.status=='SUCCESS'){
				$scope.academicVos=data.result;
				$scope.academicExtraInfo=data.extraInfo;
				$scope.showGrid=true;
				$scope.getRecommendations();//render recommendations
			}
			else if(data.status='NOT_FOUND'){
				alert("No record found for this entity.");
				$scope.academicVos=[];
				$scope.showGrid=true;
			}
			else{
				alert(data.status +":"+data.msg);
				$scope.showGrid=true;
			}
		}).error(function(){
			ERROR_LOGGER("Server Error");
		});
		
	}
	
	$scope.criteriaChanged=function(){
		$scope.showGrid=false;
		$scope.academicVos=[];
	}
	
	$scope.showSubject = function(academicVo) {
	    var selected = [];
	    if(academicVo.subjectId) {
	      selected = $filter('filter')($scope.subjects, {id: academicVo.subjectId});
	    }
	    return selected.length ? selected[0].subjectName : 'Not set';
	};
	
	$scope.showGradePoint = function(academicVo) {
	    var selected = [];
	    if(academicVo.gradePointId) {
	      selected = $filter('filter')($scope.gradePoints, {id: academicVo.gradePointId});
	    }
	    return selected.length ? selected[0].value : 'Not Set';
	};
	  $scope.checkValue = function(data, id) {
		  //validation will go here
	  };

	  // filter academicVo to show
	  $scope.filterAcademics = function(academicRow) {
	    return academicRow.rowDeleted !== true;
	  };

	  // mark user as deleted
	  $scope.deleteAcademicRow = function(cid,sid) {
		  //alert(cid);
	    var filtered = $filter('filter')($scope.academicVos, {cid: cid});
	    if (filtered.length) {
	      filtered[0].rowDeleted = true;
	      $scope.academicVos[cid].rowDeleted=true;
	    }
	  };

	  // add user
	  $scope.addAcademicRow = function() {
	    $scope.academicVos.push({
	      cid: $scope.academicVos.length+1,
	      sid: 0,
	      subjectId: null,
	      marks: null,
	      gradeId: $scope.searchCriteria.gradeId,
	      termId:  $scope.searchCriteria.termId,
	      gradePointId:0,
	      maxMarks: 100,
	      newRow:true,
	      remarks:null
	    });
	  };

	  // cancel all changes
	  $scope.cancel = function() {
	    for (var i = $scope.academicVos.length; i--;) {
	      var vo = $scope.academicVos[i];    
	      // undelete
	      if (vo.isDeleted) {
	        delete vo.isDeleted;
	      }
	      // remove new 
	      if (vo.newRow) {
	        $scope.academicVos.splice(i, 1);
	      }
	    };
	  };

	  // save edits
	  $scope.saveTable = function() {
	    var results = [];
	    for (var i = $scope.academicVos.length; i--;) {
	      var vo = $scope.academicVos[i];
	      // actually delete user
	      if (vo.rowDeleted) {
	        //$scope.academicVos.splice(i, 1);
	      }
	      // mark as not new 
	      if (vo.newRow) {
	    	  vo.newRow = true;
	      }
	      vo.termId=$scope.searchCriteria.termId;
	      vo.gradeId=$scope.searchCriteria.gradeId;
	    }
	    //Create student vo object
	    studentRecord.studentAcademics=$scope.academicVos;
	    studentRecord.searchCriteria= $scope.searchCriteria;
	    // send on server
	    var httpResult=$http.post(BASE_URL+'admin/handleRequest/studentRecord/SAVE_ACADEMICS', studentRecord);
	    httpResult.success(function(data){
	    	if(data.status="SUCCESS"){
    			$.each($scope.academicVos,function(a,b){
	    			b.newRow=false;
	    		});
    			alert("Record Saved Successfully");
    		}else{
    			alert("Records not saved, contact administrator");
    		}
	    });
	    results.push(httpResult);
	    return $q.all(results);
	  };
	}]);